﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.IO;

/// <summary>
/// Summary description for ReceiveEdi
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ReceiveEdi : System.Web.Services.WebService {

    public ReceiveEdi () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    [WebMethod]
    public int InsertObj(string fromCompany,string fromUser,string fromType,string fromNo,string toCompany,string toType,string context)
    {
        int res = 0;
        string sql = @"Insert into XWJobEdi(FromUser, FromDate, FromCompany, FromType, FromNo, ToCompany, ToUser, ToDate,ToType, ToNo, Context, status)";
        sql += " Values(";
        sql += string.Format("'{0}',",fromUser);
        sql += string.Format("'{0}',",DateTime.Now.ToString("yyyy-MM-dd"));
        sql += string.Format("'{0}',",fromCompany);
        sql += string.Format("'{0}',",fromType);
        sql += string.Format("'{0}',",fromNo);
        sql += string.Format("'{0}',",toCompany);
        sql += string.Format("'{0}',","");
        sql += string.Format("'{0}',",DateTime.Now.ToString("yyyy-MM-dd"));
        sql += string.Format("'{0}',",toType);
        sql += string.Format("'{0}',","");
        sql += string.Format("'{0}',",context);
        sql += string.Format("'{0}'","New");
        sql += ")";
        res=ExecuteSql(sql);
   
        return res;

    }

    private int ExecuteSql(string sql)
    {
        string conn = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectString"].ConnectionString;
        SqlConnection oSQLConn = new SqlConnection();
        oSQLConn.ConnectionString = conn;
        oSQLConn.Open();
        SqlCommand cmd = oSQLConn.CreateCommand();
        cmd.CommandText = sql;
        int res = cmd.ExecuteNonQuery();
        oSQLConn.Close();
        return res;
    }
    
    [WebMethod]
    public int SendEmailByImapDataSet(string fromCompany, string fromUser, string fromType, string fromNo, string toCompany, string toType, DataSet set)
    {
        string filePath = CreateSendEdi(set);
        return InsertObj(fromCompany, fromUser, fromType, fromNo, toCompany, toType, filePath);
    }
    public string CreateSendEdi(DataSet set)
    {
        string path = System.Configuration.ConfigurationManager.AppSettings["EdiPath"];
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        string fileName = path + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_Edi.txt";
        set.WriteXml(fileName, XmlWriteMode.WriteSchema);
        return fileName;
    }

}

